package cn.springcloud.fix.demo.thread;

/**
 * http://jiangzhengjun.iteye.com/blog/652269
 */
public class ThreadInterruptSample4 {

    public static void main(String[] args) throws Exception {
        final Object lock1 = new Object();
        final Object lock2 = new Object();
        Thread thread1 = new Thread(() -> deathLock(lock1, lock2));
        Thread thread2 = new Thread(() -> deathLock(lock2, lock1));

        System.out.println("Starting thread...");
        thread1.start();
        thread2.start();
        Thread.sleep(3000);
        System.out.println("Interrupting thread...");
        //interrupt()方法是不能中断死锁线程的，因为锁定的位置根本无法抛出异常：
        thread1.interrupt();
        thread2.interrupt();
        Thread.sleep(3000);
        System.out.println("Stopping application...");
    }

    static void deathLock(Object lock1, Object lock2) {
        try {
            synchronized (lock1) {
                Thread.sleep(10);
                synchronized (lock2) {// 会锁在这里，虽然阻塞了，但不会抛异常
                    System.out.println(Thread.currentThread());
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}
